package io.tij;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static util.Print.*;

class House implements Serializable{}

class Animal implements Serializable{
	private String name;
	private House houseRef;
	
	public Animal(String name, House houseRef){
		this.name = name;
		this.houseRef = houseRef;
	}
	
	public String toString(){
		return name + "[" + super.toString() + "], " + houseRef + "\n";
	}
}

public class MyWorld {
	
	public static void main(String[] args) throws IOException, ClassNotFoundException{
		House house = new House();
		List<Animal> animals = new ArrayList<Animal>();
		
		animals.add(new Animal("kkk", house));
		animals.add(new Animal("jjj", house));
		animals.add(new Animal("lll", house));
		
		print("animals: " + animals);
		
		ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
		ObjectOutputStream out1 = new ObjectOutputStream(buf1);
		out1.writeObject(animals);
		// Change animals, but 'animals2' are same as 'animals1'
		animals.add(new Animal("mmm", house));
		out1.writeObject(animals);

		ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
		ObjectOutputStream out2 = new ObjectOutputStream(buf2);
		out2.writeObject(animals);
		
		ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray()));
		print("animals1:" + in1.readObject());
		print("animals2:" + in1.readObject());
		
		ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray()));
		print("animals3:" + in2.readObject());
	}
}
